package textapp.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import textapp.dao.model.Message;
import textapp.dao.model.User;

public class MessageDao {
	public Message create(Message m) {
		EntityManager em = EMUtil.createEntityManager();
		em.getTransaction().begin();
		em.persist(m);
		em.getTransaction().commit();
		em.close();
		return m;
	}
	
	public boolean updateStatus(int messageId, int status) {
		EntityManager em = EMUtil.createEntityManager();
		Message m = em.find(Message.class, messageId);
		if ( m == null) {
			return false;
		}
		em.getTransaction().begin();
		m.setStatus(status);
		m.setModifyDate(new Date());
		em.getTransaction().commit();
		em.close();
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public List<Message> getMessagesByUserIdAndTime(int userId, long beginTimeStampMS) {
		EntityManager em = EMUtil.createEntityManager();
		User u = em.find(User.class, userId);
		if (u == null) {
			return new ArrayList<Message>();
		}
		Query q = em.createNamedQuery("Message.getByUserIdAndTime");
		q.setParameter("toUser", u);
		q.setParameter("beginTime", new Date(beginTimeStampMS));
		return q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Message> getConversationByTime(int toUserId, int fromUserId, long beginTimeStampMS) {
		EntityManager em = EMUtil.createEntityManager();
		User u = em.find(User.class, toUserId);
		User f = em.find(User.class, fromUserId);
		if (u == null || f == null) {
			return new ArrayList<Message>();
		}
		Query q = em.createNamedQuery("Message.getConversationByTime");
		q.setParameter("toUser", u);
		q.setParameter("fromUser", f);
		q.setParameter("beginTime", new Date(beginTimeStampMS));
		return q.getResultList();
	}
	
	// TODO: update status bulk messages
}
